var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../db.js')
var md5 = require('md5-nodejs')
var multer = require('multer');
var router = express.Router()

// 渲染列表
router.get('/list', async function (req, res) {
    var {
        currentPage,
        pageSize,
        keyword,
        sort = "desc",
        orderby = "id"
    } = req.query;
    if (!currentPage) {
        currentPage = 0
    }

    if (!pageSize) {
        pageSize = 20
    }
    var sql = `select * from jiesuan`
    var sql_count = "select count(*) as total from jiesuan";

    var num = currentPage * pageSize;
    if (keyword) {
        sql_count += ` where name like '%${keyword}%'`;
        sql += ` where name like '%${keyword}%'`;
    }
    // console.log(sql)
    if (orderby) {
        sql += ` order by ${orderby} ${sort}`;
    }
    sql += ` limit ${num},${pageSize}`
    const data = await Promise.all([db.doSQL(sql), db.doSQL(sql_count)])
    res.send(db.handerResult(data[0].data, data[1].data))
})



// 新增
router.post('/addList', urlencodedParser, async function (req, res) {
    var {
        dingdan,
        name,
        price,
        num,
        zhuangtai,
        cid
    } = req.body
    var sql = `insert into jiesuan (dingdan, name, price, num, zhuangtai, cid) values ("${dingdan}","${name}","${price}","${num}","${zhuangtai}","${cid}")`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// pc删除
router.get('/delList', async function (req, res) {
    var {
        cid,
        id
    } = req.query
    var sql;
    if (id) {
        sql = `delete from jiesuan where id in (${id})`
    } else {
        sql = `delete from jiesuan where cid in (${cid})`
    }
    const data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// 修改
router.post('/updateList', urlencodedParser, async function (req, res) {
    var {
        cid,
        num,
    } = req.body
    var sql = `update jiesuan set num='${num}'  where cid='${cid}'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

//管理系统修改
router.post('/xgList', urlencodedParser, async function (req, res) {
    var {
        id,
        name,
        num,
        price,
        zhuangtai
    } = req.body
    console.log(req.body)
    var sql = `update jiesuan set name='${name}', price='${price}', num='${num}' , zhuangtai='${zhuangtai}' where id='${id}'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})


//修改状态(已购买或者未购买)
router.post('/updateState', urlencodedParser, async function (req, res) {
    var {
        cid,
        num
    } = req.body
    var sql = `update jiesuan set num='${num}',zhuangtai='${1}'  where cid='${cid}' and zhuangtai='0'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})


module.exports = router;